package weaver.filter.login;

import com.asn1.ocsp.Request;
import com.engine.edc.util.UUID;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;



public class LoginExtension {
    private static final String UID_COOKIE = "extloginid";
    private static final String AES_KEY = "ext";


    public static void dealChaoshi(HttpServletRequest request, HttpServletResponse response) {
        String uuid = UUID.randomKey();
        // new BaseBean().writeLog("chaoshi*****" + uuid);
        String uidcookie = Util.getCookie(request, "extloginid");
        if (StringUtils.isEmpty(uidcookie)) {
         //  new BaseBean().writeLog("没有获取到extloginid+++"+request.getRequestURI());
            return;
        }

        String uid = "";
        if (LoginExtensionFilter.isAES)
            try {
                uid = AESCoder.decrypt(uidcookie, "ext");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        else {
            uid = uidcookie;
        }

        if ("".equals(uid)) {
         //   new BaseBean().writeLog(uidcookie + "uidcookie:" + uid);
         //     new BaseBean().writeLog("###没有解析到uid，无法补偿会话###");
            return;
        }
        // new BaseBean().writeLog(uuid + "create user ####" + uid);
        //new BaseBean().writeLog(("###获取到extloginid=" + uid + "超时补偿构建会话"));
        createUser(request, response, uid);

    }

    private static void createUser(HttpServletRequest request, HttpServletResponse response, String uid) {
        String uidcookie = Util.getCookie(request, "extloginid");

        boolean isAdmin = false;
        RecordSet rs = new RecordSet();
        rs.execute("SELECT * FROM HrmResourceManager WHERE id=" + uid);
        if (rs.next()) {
            isAdmin = true;
        } else {
            rs.execute("SELECT * FROM HrmResource WHERE id=" + uid);
            if (!rs.next()) {
                return;
            }
        }

        User user = new User();
        user.setUid(rs.getInt("id"));
        user.setLoginid(rs.getString("loginid"));
        user.setFirstname(rs.getString("firstname"));
        user.setLastname(rs.getString("lastname"));
        user.setAliasname(rs.getString("aliasname"));
        user.setTitle(rs.getString("title"));
        user.setTitlelocation(rs.getString("titlelocation"));
        user.setSex(rs.getString("sex"));
        String languageidweaver = Util.null2String(rs.getString("systemlanguage"), "7");
    /*
    int islanguid = 7;
    String languid = "7";
    boolean ismutilangua = Util.isEnableMultiLang();
    if (ismutilangua) {
      islanguid = Util.getIntValue(request.getParameter("islanguid"), 0);
      if (islanguid == 0) {
        islanguid = 7;
      }
    }
     */
        Calendar today = Calendar.getInstance();
        String currentdate = Util.add0(today.get(1), 4) + "-" + Util.add0(today.get(2) + 1, 2) + "-" + Util.add0(today.get(5), 2);
        String login_type = Util.null2String(request.getParameter("logintype"), "1");
        String startdate = rs.getString("startdate");
        String enddate = rs.getString("enddate");
        user.setLanguage(Util.getIntValue(languageidweaver, 7));
        user.setTelephone(rs.getString("telephone"));
        user.setMobile(rs.getString("mobile"));
        user.setMobilecall(rs.getString("mobilecall"));
        user.setEmail(rs.getString("email"));
        user.setCountryid(rs.getString("countryid"));
        user.setLocationid(rs.getString("locationid"));
        user.setResourcetype(rs.getString("resourcetype"));
        user.setStartdate(startdate);
        user.setEnddate(enddate);
        user.setContractdate(rs.getString("contractdate"));
        user.setJobtitle(rs.getString("jobtitle"));
        user.setJobgroup(rs.getString("jobgroup"));
        user.setJobactivity(rs.getString("jobactivity"));
        user.setJoblevel(rs.getString("joblevel"));
        user.setSeclevel(rs.getString("seclevel"));
        user.setUserDepartment(Util.getIntValue(rs.getString("departmentid"), 0));
        user.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
        user.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
        user.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
        user.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
        user.setManagerid(rs.getString("managerid"));
        user.setAssistantid(rs.getString("assistantid"));
        user.setPurchaselimit(rs.getString("purchaselimit"));
        user.setCurrencyid(rs.getString("currencyid"));
        user.setLastlogindate(currentdate);
        user.setLogintype(login_type);
        user.setAccount(rs.getString("account"));
        user.setIsAdmin(isAdmin);

        String serialNo = Util.null2String(rs.getString("serial"));

        int needusb = rs.getInt("needusb");

        String userUsbType = Util.null2String(rs.getString("userUsbType"));
        needusb = (userUsbType.equals("2")) || (userUsbType.equals("3")) ? 1 : 0;
        user.setNeedusb(needusb);
        user.setSerial(serialNo);
        user.setLoginip(Util.getIpAddr(request));
        String weaver_login_type = Util.null2String(request.getSession(true).getAttribute("weaver_login_type"));

        request.getSession(true).setAttribute("weaver_login_type", weaver_login_type);
        request.getSession(true).setAttribute("weaver_user@bean", user);
        request.getSession(true).setAttribute("rtxlogin", "1");
        Util.setCookie(response, "loginidweaver", user.getUID() + "", -1);
        Util.setCookie(response, "languageidweaver", Util.null2s(languageidweaver, "7"), -1);
        Util.setCookie(response, "extloginid", uidcookie, -1);

        User uu = (User) request.getSession().getAttribute("weaver_user@bean");

     //   new BaseBean().writeLog(uu.getUID() + "User####" + uu);
    }

    public static void dealChuanhao(String currUid, HttpServletRequest request, HttpServletResponse response) {
        //   new BaseBean().writeLog("chuanhao*****");
        String uri = request.getRequestURI();
        String uidcookie = Util.getCookie(request, "extloginid");
        if (StringUtils.isEmpty(uidcookie)) {
            User userBean = (User) request.getSession().getAttribute("weaver_user@bean");
            updateCookie(userBean.getUID() + "", response);
           // new BaseBean().writeLog("创建extloginid:" + userBean.getUID() + "  " + uri);
            return;
        }

        for (String url : LoginExtensionFilter.logoutUrls) {
            if (uri.indexOf(url) > -1) {
                User userBean = (User) request.getSession().getAttribute("weaver_user@bean");
                new BaseBean().writeLog("清空extloginid:" + userBean.getUID() + "##" + uri);
                updateCookie("", response);
                return;
            }
        }

        String uid = "";
        if (LoginExtensionFilter.isAES)
            try {
                uid = AESCoder.decrypt(uidcookie, "ext");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        else {
            uid = uidcookie;
        }

        if (!LoginExtensionFilter.enblechuanhao) {
            return;
        }

        if ((uid != null) && (!uid.equals(currUid)))
         //   new BaseBean().writeLog(("###获取到extloginid=" + uidcookie + "串号补偿"));
        createUser(request, response, uid);
    }

    public static void updateCookie(String uid, HttpServletResponse response) {
        String uiddes = "";
        if ((LoginExtensionFilter.isAES) && (!StringUtils.isEmpty(uid)))
            try {
                uiddes = AESCoder.encrypt(uid, "ext");
            } catch (Exception e) {
                e.printStackTrace();
            }
        else {
            uiddes = uid;
        }
      //  new BaseBean().writeLog("updateCookie----" + uiddes);
        Util.setCookie(response, "extloginid", uiddes, -1);
    }

    public static void clearCookie(HttpServletRequest request, HttpServletResponse response) {
        new BaseBean().writeLog("Timeout : clearCookie----");
     //   Util.setCookie(response, "ecology_JSessionid", "", 0);
     //   Util.setCookie(response, "JSessionid", "", 0);

        try {
            response.addHeader("Set-Cookie", "__clusterSessionIDCookieName=" + Util.getCookie(request, "__clusterSessionIDCookieName") + ";expires=Thu, 01-Dec-1994 16:00:00 GMT;Path=/;HttpOnly");
            Cookie[] cookiess = request.getCookies();
            if (null == cookiess) {
                System.out.println("没有cookie==============");
            } else {
                for (Cookie logincookie : cookiess) {
                    if (logincookie.getName().equalsIgnoreCase("__clustersessioncookiename")
                            || logincookie.getName().equalsIgnoreCase("ecology_ajsessionid")
                            || logincookie.getName().equalsIgnoreCase("ecology_jsessionid")
                            || logincookie.getName().equalsIgnoreCase("jsessionid")
                            || logincookie.getName().equalsIgnoreCase("__clustersessionidcookiename")
                    ) {
                        logincookie.setValue(null);
                        logincookie.setMaxAge(0);// 立即销毁cookie
                        logincookie.setPath("/");
                        response.addCookie(logincookie);
                        new BaseBean().writeLog("!!销毁cookie："+logincookie.getName());
                    }
                }
            }


        } catch (Exception e) {
        }

    }

}